/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "File.h"

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


File::File(const std::string & iFileName)
{
   _fs.open(iFileName.c_str());
}

File::File(const char * const iFileName)
{
   _fs.open(iFileName);
}

File::~File()
{
   if(_fs.is_open())
      _fs.close();
}

string File::readLine()
{
   unsigned int nbCharRead = 0;
   char         line[256];

   _fs.getline(line, 256); 

   nbCharRead = _fs.gcount();

   if(nbCharRead > 1)
   {
      //We have read at least 2 chars, so we can move on the cursor
      _fs.seekg(nbCharRead - 1, ios_base::cur);
   }

   return string(line);
}

string File::readAll()
{
   //Save curent position to restore after the read
   unsigned int curPos = _fs.tellg();
   
   
   _fs.seekg(0, ios::end);
   
   unsigned int length = _fs.tellg();

   _fs.seekg(0, ios::beg);
   
   // allocate memory:
   char * buffer = new char [length];

   // read data as a block:
   _fs.read (buffer,length);

   string str(buffer);

   delete buffer;
   buffer = NULL;

   //Restore old position
   _fs.seekg(curPos, ios::beg);
   
   return str;
}

string File::readAllSincePosition()
{
   //Save curent position to restore after the read
   unsigned int curPos = _fs.tellg();

   _fs.seekg(0, ios::end);
   
   unsigned int length = _fs.tellg();
   length -= curPos;

   // allocate memory:
   char * buffer = new char [length+1]; //Increase one for the \0
   
   //Restore old position
   _fs.seekg(curPos, ios::beg);

   // read data as a block:
   _fs.read (buffer,length); //Don't read the \0

   buffer[length] = 0;

   string str(buffer);

   delete buffer;
   buffer = NULL;

   //Restore old position
   _fs.seekg(curPos, ios::beg);

   return str;
}



bool File::isAtTheEnd() const
{
   return _fs.eof();
}
